/**
 * iframe页面通信枢纽，父页面与iframe页面保持一致
 */

enum HUB_SCOPE {
	USER = 'user',
	EDIT = 'edit',
	PREVIEW = 'preview',
	ASSET = 'asset'
};

interface IMessageData<T,D> {
	scope : HUB_SCOPE,
	type : T,
	data : D
}

class MessageHub<TYPE>{

	private userWnd : Window;
	private scope : HUB_SCOPE;

	constructor(userWindow : Window, scope : HUB_SCOPE) {
		this.userWnd = userWindow;
		this.scope = scope;
	}

	public dispatch<D>(type : TYPE, data : D) : void {
		const msg : IMessageData<TYPE,D> = {
			scope: this.scope,
			type: type,
			data: data
		};
		this.userWnd.postMessage(msg, this.userWnd.origin);
	}

	public listen<D>(type : TYPE, callback : { (data : IMessageData<TYPE,D>) : void }) : void {
		this.userWnd.addEventListener('message', (event : MessageEvent) => {
			if (event.origin !== window.origin) {
				console.log('message from illegal origin')
				return;
			}
			const data : IMessageData<TYPE,D> = event.data;
			if (event.data.scope !== this.scope) {
				return;
			}
			if (data.type !== type) {
				return;
			}
			callback(data);
		});
	}

}


export { MessageHub, HUB_SCOPE };
export type { IMessageData };